package cn.com.callback

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.elite.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.Util;

/**
 * 功能介绍：定时调用此接口，将documentout中符合条件的短信插入水务数据库短信表，由水务进行短信发送；
 */

public class InsertSZWaterDB implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(InsertSZWaterDB.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){

		log.debug("-------------------------start  InsertSZWaterDB------------------------");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		def templistID = request.getParameter("templistID");
		log.debug("templistID=" + templistID);
		def templistFlag = request.getParameter("templistFlag");
		log.debug("templistFlag=" + templistFlag);

		try{
			def SMSCount = 0;
			def message;
			def msg;

			if(templistFlag.equals("cancel")){
				log.debug("作废批次开始执行------------------------------");

				//查询批次下所有数据
				def allDocumentoutSQL = "Select Count(*) Allcount ,Sum(Case When Passflag='1' Then 1 Else 0 End) Sendcount From Documentout Where Sms_Guid = '" + templistID + "'";
				log.debug("查询批次下所有数据SQL:" + allDocumentoutSQL);

				List allDocumentoutList = eliteBean.chaxun_sql(allDocumentoutSQL, "dataSource");
				def allcount = allDocumentoutList.get(0).get("Allcount");
				def sendcount = allDocumentoutList.get(0).get("Sendcount");
				log.debug("查询批次下所有数据SQL执行结果:总数:" + allcount + " 已发送:" + sendcount);

				if(allcount == sendcount){
					msg = "当前批次共有" + allcount + "条数据，已发送" + sendcount + "条数据，批次无法取消短信发送！";
					log.debug("msg=" + msg);
					message = "{\"message\":\""+msg+"\"}";
				}else if(allcount > sendcount){
					def cancelDocumentoutSQL = "Update Documentout Set Passflag = '2', Result = 'CANCEL' Where Sms_Guid = '" + templistID + "' And Passflag is null";
					log.debug("cancelDocumentoutSQL="+cancelDocumentoutSQL);

					def cancelDocumentouFlag = eliteBean.update(cancelDocumentoutSQL,"dataSource");
					if(cancelDocumentouFlag >= 0){
						msg= "当前批次共有"+allcount+"条数据，已发送"+sendcount+"条数据,取消"+cancelDocumentouFlag+"条数据！";
						log.debug("msg=" + msg);
						message = "{\"message\":\""+msg+"\"}";
					}
				}

			}else{
				log.debug("发送短信开始执行------------------------------");
				//def selectDocumentoutSQL = "Select top 100 Documentout_Guid, Documentto, Documentpath, Expectedstartdate, Expectedstartdate,stringfield1,sms_guid,case when STRINGFIELD1='人工短信' then 1 when STRINGFIELD1='工单' then 2 when STRINGFIELD1='通讯录短信' then 3 when STRINGFIELD1='人工批次发送' then 4 end  as priority From Documentout Where Expectedstartdate <= Getdate() And Passflag Is Null And Doctype = '3' and LEN(Documentpath)<=500 ORDER BY priority,CREATEDDATE";
				def selectDocumentoutSQL = "Select top 100 Documentout_Guid, Documentto, Documentpath, Expectedstartdate, Expectedstartdate,stringfield1,sms_guid,case when STRINGFIELD1='人工短信' then 1  when STRINGFIELD1='工单' then 2 when STRINGFIELD1='通讯录短信' then 3 when STRINGFIELD1='智慧停水发送' then 4 when STRINGFIELD1='人工批次发送' then 4 end  as priority From Documentout Where Expectedstartdate <= Getdate() And Passflag Is Null And Doctype = '3' and ISNUMERIC(DOCUMENTTO)=1 ORDER BY priority,CREATEDDATE";
				log.debug("查询待发送短信selectDocumentoutSQL="+selectDocumentoutSQL);

				List selectDocumentoutList = eliteBean.chaxun_sql(selectDocumentoutSQL, "dataSource");
				def ListNum = selectDocumentoutList.size();
				log.debug("待发送短信数量ListNum=" + ListNum);

				if(ListNum > 0){
					for(int i = 0; i<ListNum; i++) {
						Map selectDocumentoutSQLMap = selectDocumentoutList.get(i);

						def documentout_guid = selectDocumentoutSQLMap.get("Documentout_Guid");
						def documentto = selectDocumentoutSQLMap.get("Documentto");
						def DOCUMENTPATH = selectDocumentoutSQLMap.get("Documentpath");
						//处理短信内容存在单引号
						def regexp = "\'";						
						DOCUMENTPATH = DOCUMENTPATH.replaceAll(regexp, "");
						
						def EXPECTEDSTARTDATE = selectDocumentoutSQLMap.get("Expectedstartdate");
						def stringfield1 = selectDocumentoutSQLMap.get("stringfield1");//短信类型批次名称
						def sms_guid = selectDocumentoutSQLMap.get("sms_guid");//批量短信导入批次号
						
						def insertMobiletempSQL="";
						def insertMobiletempFlag="";
						def insertSendFlag="";
						def insertgxsendlisttempFlag="";
						if(stringfield1!='人工批次发送'){
						// 插入水务ITSV.szwaterDB.DBO.mobiletemp_1表
						 insertMobiletempSQL = "Insert Into Itsv.Szwaterdb.Dbo.Mobiletemp_1 (Realname, Mobile, Loginname, Bh) Values ('', '" + documentto + "', '', '" + documentout_guid + "')";
						log.debug("插入短信平台MobileTemp_1表SQL:" + insertMobiletempSQL);
						 insertMobiletempFlag = eliteBean.update(insertMobiletempSQL, "dataSource");
						log.debug("插入短信平台MobileTemp_1表SQL执行结果:" + insertMobiletempFlag);

						// 插入水务ITSV.szwaterDB.DBO.sendlist表
						def insertSendSQL = "Insert Into Itsv.Szwaterdb.Dbo.Sendlist (Content, Sendtime, Schtime, Smscount, Subcode, Bh, Status, Server, Depid, Isread, Typework, Loginname) Values ('" + DOCUMENTPATH + "', '" + EXPECTEDSTARTDATE + "', '" + EXPECTEDSTARTDATE + "', 1, 1, '" + documentout_guid + "', 0, 1, 1, 0, 15, 'linzm')";
						log.debug("插入短信平台SendList表SQL=" + insertSendSQL);
						insertSendFlag = eliteBean.update(insertSendSQL, "dataSource");
						log.debug("插入短信平台SendList表SQL执行结果:" + insertSendFlag);
						}else{
						//批量短信发送按照催缴模式发送
						// 插入水务ITSV.szwaterDB.DBO.gxsendlist
						def insertgxsendlisttempSQL = "insert into ITSV.szwaterDB.DBO.gxsendlist (content,sendtime,loginname,mobile,typework,bh,status,isbirthday,sms_guid,depid) Values ('" + DOCUMENTPATH + "', '" + EXPECTEDSTARTDATE + "','API','" + documentto + "','CRM批量发送短信','" + documentto + "', 0, 0,'" + sms_guid + "',1)";
						log.debug("插入短信平台gxsendlisttemp表SQL:" + insertgxsendlisttempSQL);
						insertgxsendlisttempFlag = eliteBean.update(insertgxsendlisttempSQL, "dataSource");
						log.debug("插入短信平台gxsendlisttemp表SQL执行结果:" + insertgxsendlisttempFlag);
						}
						def updateDocumentouFlag="";
						if(insertSendFlag == 1 && insertMobiletempFlag == 1){
							SMSCount++;
							def updateDocumentoutSQL = "Update Documentout Set Passflag = '1', Lasttrydatetime = Getdate(), Modifiedby = 'SELITE', Modifieddate = Getdate(), Faildescription = '" + insertMobiletempFlag + "' + '/' + '" + insertSendFlag + "' Where Documentout_Guid = '" + documentout_guid + "'";
							log.debug("短信平台回写Documentout表SQL:" + updateDocumentoutSQL);

							updateDocumentouFlag = eliteBean.update(updateDocumentoutSQL, "dataSource");
							log.debug("短信平台回写Documentout表SQL执行结果:" + updateDocumentouFlag);
						}else if(insertgxsendlisttempFlag==1) {//批量短信发送按照催缴模式发送
							SMSCount++;
							def updateDocumentoutSQL = "Update Documentout Set Passflag = '1', Lasttrydatetime = Getdate(), Modifiedby = 'SELITE', Modifieddate = Getdate(), Faildescription = '" + insertgxsendlisttempFlag + "' Where Documentout_Guid = '" + documentout_guid + "'";
							log.debug("短信平台回写Documentout表SQL:" + updateDocumentoutSQL);

							updateDocumentouFlag = eliteBean.update(updateDocumentoutSQL, "dataSource");
							log.debug("短信平台回写Documentout表SQL执行结果:" + updateDocumentouFlag);
						}
					}
					msg = "当前批次共有" + ListNum + "条数据，成功插入" + SMSCount + "条！";
					log.debug("当前需要发送短信的数据处理结果:" + msg);
					//智慧停水短信 发送成功标识更新
					def waterOffSmsbatchSQL = "update waterOffSmsbatch set status=2,finishdate=GETDATE() where sms_guid in (select DISTINCT sms_guid from Documentout where STRINGFIELD1='智慧停水发送' and Passflag = '1' and EXPECTEDSTARTDATE>GETDATE()-1 group by sms_guid)";
					log.debug("智慧停水短信发送状态waterOffSmsbatch表SQL:" + waterOffSmsbatchSQL);
					
					def waterOffSmsbatchFlag = eliteBean.update(waterOffSmsbatchSQL, "dataSource");
					log.debug("智慧停水短信发送状态更新waterOffSmsbatch表SQL执行结果:" + waterOffSmsbatchFlag);

					message = "{\"message\":\"" + msg + "\"}";
				}else {
					message = '{"message":"当前批次下没有需要发送短信的数据"}';
				}
			}

			return message;
		}catch(Exception e){
			log.error("InsertSZWaterDB异常信息：" ,e);
		}
	}
}